﻿Imports Mystery

''' <summary>
''' a basic attricute to create user control for properties
''' if the control is always the same give implementing_type 
''' if the control changes in function of the content data give the selector_type
''' </summary>
''' <remarks></remarks>
Public Class ContentPropertBaseIOAttr
    Inherits MysteryPropertyAttribute

    Public Property implementing_type As Type
    Public Property selector_type As Type

    Private _activator As IActivator

    Private _property_type As Type

    Private Shared Property _selector_ref_type As Type = GetType(IContentDrivenSelector(Of UserControl))

    Public Overrides Sub setUp()
        _property_type = used_in.PropertyType.GetGenericArguments.FirstOrDefault()

        'first let's if we have a selector
        If selector_type IsNot Nothing Then
            selector_type.GetInterfaceMap(_selector_ref_type)
            _activator = getGlobalObject(Of FastActivator).getActivator(selector_type)
        ElseIf implementing_type IsNot Nothing Then
            If Not implementing_type.IsSubclassOf(GetType(UserControl)) Then
                Throw New Exception(_property_type.FullName & " have a wrong implementing_type for " & Me.GetType.Name)
            End If
            _activator = getGlobalObject(Of FastActivator).getActivator(implementing_type)
        Else
            Dim cd As PropertyControlDefaults = getGlobalObject(Of PropertyControlDefaults)()
            implementing_type = cd.getDefaultViewFor(_property_type)
            _activator = getGlobalObject(Of FastActivator).getActivator(implementing_type)
        End If


        If implementing_type Is Nothing AndAlso selector_type Is Nothing Then
            Throw New Exception("no interface found for " & _property_type.FullName)
        End If


    End Sub

    Public Function createControl(content As IContent) As UserControl
        Dim control As UserControl
        If selector_type IsNot Nothing Then
            control = DirectCast(_activator.createInstance(), IContentDrivenSelector(Of UserControl)).getIt(content)
        Else
            control = _activator.createInstance()
        End If

        If TypeOf (control) Is IPropertyControl Then
            Dim pc As IPropertyControl = control
            pc.property_info = used_in
            pc.content = content
        End If

        Return control
    End Function
End Class
